package com.mycloud.util;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * User: hossein bahramian
 * Date: Oct 18, 2011
 * Time: 4:51:07 PM
 */
public class FileUtil {

    private static Logger logger = Logger.getLogger(FileUtil.class);
    private static File file;

    /**
     * @param file a file in classpath
     * @return
     */
    public static String readClassPath(String file) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("file is [" + file + "]");
        }
        return IOUtils.toString(FileUtil.class.getClassLoader().getResourceAsStream(file));

    }

    public static List<String> readFileAsList(String file) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("file is [" + file + "]");
        }

        return readFileAsList(new FileInputStream(file));
    }

    public static List<String> readFileAsList(InputStream file) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("file is [" + file + "]");
        }

        List<String> list = new ArrayList<String>();
        Scanner scanner = new Scanner(file, "utf-8");
        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                list.add(line);
            }
        }
        finally {
            scanner.close();
        }

        return list;
    }



    /**
     * @param file a file in a directory
     * @return
     * @throws IOException
     */
    public static String readFile(String file) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("file is [" + file + "]");
        }

        StringBuilder text = new StringBuilder();
        final String NEW_LINE = System.getProperty("line.separator");
        Scanner scanner = new Scanner(new FileInputStream(file), "utf-8");
        try {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
//                logger.debug(line);
                text.append(line).append(NEW_LINE);
            }
        }
        finally {
            scanner.close();
        }

        return text.toString();

//        return IOUtils.toString(new FileReader(file));

    }

    public static String getAttachmentPath(long userId) throws Exception {
        return "directories" + File.separatorChar +
                "users" + File.separatorChar + userId +
                File.separatorChar + ".outattach" + File.separatorChar;
    }

    public static String getUserMailPath(long userId) throws Exception {
        return "directories" + File.separatorChar + "users" +
                File.separatorChar + userId +
                File.separatorChar + ".attach" + File.separatorChar;
    }

    public static String getCobrandMailPath(long cobrandId) throws Exception {
        return "directories" + File.separatorChar + "cobrands" +
                File.separatorChar + cobrandId +
                File.separatorChar + "sharedmail" + File.separatorChar;
    }

    /**
     * tries the specified filePath and fileName does exist or not. if exist, it tries to rename the filename, and check again.
     *
     * @param filePath
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getFileName(String filePath, String fileName, String fileExt) throws Exception {

        File file = new File(filePath + fileName + "." + fileExt);
        if (file.exists() == false)
            return fileName + "." + fileExt;

        int i = 1;
        while (file.exists()) {
            file = new File(filePath + fileName + "(" + i++ + ")." + fileExt);
            if (i > 10000) {
                throw new Exception("Error: 10000 mail of the same name.  Quitting:" + filePath + fileName);
            }
        }
        return fileName + "(" + i++ + ")." + fileExt;
    }

    public static void appendString(File file, String str) {
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fstream = new FileWriter(file, true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(str);
            out.newLine();
            out.close();
        } catch (Throwable t) {

        }
    }

    public static void appendString(String str) {
        try {
            if (file == null || !file.exists()) {
                file = File.createTempFile("integration-", ".txt");
                System.out.println("file:  " + file.getAbsolutePath());
            }
            appendString(file, str);
        }
        catch (Throwable t) {

        }
    }

}


